using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Core.BOL;
using Core.DAL;
using Core.Extentions;

namespace ScoutNET.Controllers
{
    public class NewsController : ApplicationController
    {
        SectionRepository sr = new SectionRepository();
        NewsRepository nr = new NewsRepository();
        MailToGenerateRepository mtgr = new MailToGenerateRepository();

        #region Properties
        private string MetaThumbnail { get { return ConfigurationManager.AppSettings["SiteUrl"] + "/Design/Images/TemplateSwitcher/logo.png"; } }
        #endregion

        #region Views
        public ActionResult Index(string systemName, int? page)
        {
            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName);
            ViewData["PageTitle"] = Resources.News_Index_Title.Replace("[SECTION]", section.ToLower());
            ViewData["PageDescription"] = Resources.News_Index_Description;
            ViewData["MetaThumbnail"] = this.MetaThumbnail;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);
            ViewData["SystemName"] = systemName;

            //Breadcrumb
            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.News_Index_Breadcrumb.Replace("[SECTION]", section.ToLower());
            ViewData["Breadcrumb"] = saBreadcrumb;

            int itemPage = 10;
            Double totalItems = Convert.ToDouble(nr.GetCountNews(systemName));
            int totalPages = (Int32)Math.Ceiling(totalItems / itemPage);
            int pageID = (page == null || page == 0) ? 1 : (int)page;
            pageID = (page > totalPages) ? totalPages : pageID;
            int skipItem = (pageID - 1) * itemPage;
            List<tSite_New> lNews = nr.GetNewsBySectionName(systemName, skipItem, itemPage);

            if(lNews.Count > 0)
            {
                ViewData["TotalPages"] = totalPages;
                ViewData["TotalItems"] = lNews.Count;
                ViewData["Page"] = pageID;

                return View("Index", lNews);
            }
            else
            {
                ViewData["ErrorMessage"] = Resources.News_Index_Error_NoItem;
                return View("Error");
            }
        }

        public ActionResult Details(string systemName, int id)
        {
            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);

            tSite_New news = nr.GetNewsByID(id);
            string section = sr.GetSectionNameBySystemName(systemName);

            if (news != null)
            {
                // Meta Tag
                ViewData["PageTitle"] = Resources.News_Details_Title.Replace("[SECTION]", section).Replace("[NEWS_TITLE]", news.Title);
                ViewData["PageDescription"] = news.News.ClearHTMLTags().ResizeText(250, string.Empty);
                ViewData["MetaThumbnail"] = this.MetaThumbnail;

                //Breadcrumb
                string[] saBreadcrumb = new String[3];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.News_Index_Breadcrumb.Replace("[SECTION]", section.ToLower()), "SectionIndex", "Index", "News", null, null);
                saBreadcrumb[2] = news.Title;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PrevNews"] = nr.GetPreviousNews(news.InsertDate, 1, news.SID).SingleOrDefault();
                ViewData["NextNews"] = nr.GetNextNews(news.InsertDate, 1, news.SID).SingleOrDefault();
                
                return View("Details", news);
            }
            
            return View("Error404");
        }

        public ActionResult Confirm()
        {
            ViewData["Action"] = "Insert";

            return View("Confirm");
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Create(string systemName)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(systemName);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Create", new { systemName = adminSection });
            }
            ViewData["SystemName"] = systemName;

            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.News_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.News_Create_Description.Replace("[SECTION]", section);
            ViewData["UserType"] = ut;

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.News_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "News", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.News_Create_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(string systemName, FormCollection fc)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(systemName);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Create", new { systemName = adminSection });
            }
            ViewData["SystemName"] = systemName;

            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.News_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.News_Create_Description.Replace("[SECTION]", section);
            ViewData["UserType"] = ut;

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.News_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "News", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.News_Create_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (ValidateNewNews(fc))
            {
                tSite_New n = new tSite_New();
                n.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                n.SID = sr.GetSectionID(systemName);
                n.News = Server.HtmlDecode(fc["Text"]).CleanWordTags();
                n.Title = Server.HtmlDecode(fc["Title"]);
                nr.InsertNews(n);
                nr.Save();

                // Add user mail
                tMail_ToGenerate tg = new tMail_ToGenerate();
                tg.Action = this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
                tg.ItemID = n.ID;
                tg.SID = n.SID;
                tg.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                mtgr.InsertMail(tg);
                mtgr.Save();

                ViewData["NewsID"] = n.ID;
                ViewData["ValidationMessage"] = Resources.News_Create_Validation.Replace("[USERNAME]", User.Identity.Name.UppercaseFirst());
                return View("Validation");
            }
            else
            {
                return View();
            }
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Delete(string systemName, int id)
        {
            ViewData["Action"] = "Delete";
            ViewData["ID"] = id;

            return View("Confirm");
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        public ActionResult Delete(string systemName, FormCollection fc)
        {
            nr.DeleteNews(int.Parse(fc["id"]));
            nr.Save();

            return new EmptyResult();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Edit(string systemName, int id)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(systemName);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Create", new { systemName = adminSection });
            }
            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = ut;

            // Meta Tag
            tSite_New n = nr.GetNewsByID(id);
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.News_Edit_Title.Replace("[TITLE]", n.Title);
            ViewData["PageDescription"] = Resources.News_Edit_Description.Replace("[TITLE]", n.Title);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.News_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "News", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.News_Edit_Breadcrumb.Replace("[TITLE]", n.Title);
            ViewData["Breadcrumb"] = saBreadcrumb;

            return View(n);
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(string systemName, int id, FormCollection fc)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(systemName);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Create", new { systemName = adminSection });
            }
            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = ut;

            // Meta Tag
            tSite_New n = nr.GetNewsByID(id);
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.News_Edit_Title.Replace("[TITLE]", n.Title);
            ViewData["PageDescription"] = Resources.News_Edit_Description.Replace("[TITLE]", n.Title);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.News_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "News", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.News_Edit_Breadcrumb.Replace("[TITLE]", n.Title);
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (ValidateNewNews(fc))
            {
                n.SID = sr.GetSectionID(systemName);
                n.News = Server.HtmlDecode(fc["Text"]).CleanWordTags();
                n.Title = Server.HtmlDecode(fc["Title"]);
                nr.Save();

                ViewData["ValidationMessage"] = Resources.News_Edit_Validation.Replace("[USERNAME]", User.Identity.Name.UppercaseFirst());
                ViewData["NewsID"] = id;
                return View("Validation");
            }
            
            return View(n);
        }
        #endregion

        #region Methodes
        private bool ValidateNewNews(FormCollection fc)
        {
            ModelState.SetModelValue("title", ValueProvider.GetValue("title"));
            ModelState.SetModelValue("text", ValueProvider.GetValue("text"));
            
            if (String.IsNullOrEmpty(fc["title"]))
            {
                ModelState.AddModelError("title", Resources.News_Create_Error_Title);
            }
            if (String.IsNullOrEmpty(fc["text"]))
            {
                ModelState.AddModelError("text", Resources.News_Create_Error_Texte);
            }
            return ModelState.IsValid;
        }
        #endregion
    }
}
